package com.jin_mo.custom.adapter.find_id;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.moudle.custom.R;

import org.jetbrains.annotations.NotNull;

import java.util.List;

public abstract class RVBaseAdapter<T> extends RecyclerView.Adapter<RVBaseViewHolder> {

    /**
     * 普通的item
     */
    private static final int TYPE_ITEM = 1;
    /**
     * 空布局的item
     */
    private static final int TYPE_EMPTY = 2;
    /**
     * 当前点击位置
     */
    public int currentPosition = -1;

    /** 是否是最后一页，默认为false，用于分页加载功能 */
    private boolean mLastPage;

    public List<T> mList;
    /**
     * 是否显示空布局，默认显示
     */
    private FrameLayout mEmptyLayout;

    /**
     * 空不局
     */
    private int nullLayoutId = R.layout.adapter_null;

    /**
     * 点击事件
     */
    private OnItemClickListener<T> mOnItemClickListener;
    /**
     * 长按事件
     */
    private OnItemLongClickListener<T> mOnItemLongClickListener;

    public RVBaseAdapter(@NotNull List<T> lists) {
        this.mList = lists;
    }

    public RVBaseAdapter() {

    }

    /**
     * 刷新数据-设置新的数据
     *
     * @param list
     */
    public void refreshData(List<T> list) {
        this.mList = list;
        notifyDataSetChanged();
    }

    /**
     * 设置新的数据但是不刷新
     * @param list
     */
    public void setNewData(List<T> list) {
        this.mList = list;
    }

    /**
     * 追加一些数据
     */
    public void addData(List<T> data) {
        if (data == null || data.size() == 0) {
            return;
        }

        if (mList == null || mList.size() == 0) {
            refreshData(data);
            return;
        }

        mList.addAll(data);
        notifyItemRangeInserted(mList.size() - data.size(), data.size());
    }

    /** 删除数据*/
    public void removeData(int position) {
        mList.remove(position);
        //删除动画
        notifyItemRemoved(position);
        notifyDataSetChanged();
    }


    /**
     * 设置当前位置
     *
     * @param currentPosition
     */
    public void setCurrentPosition(int currentPosition) {
        this.currentPosition = currentPosition;
        notifyDataSetChanged();
    }


    /**
     * 获取数据总数
     * @return
     */
    public int getCount() {
        if (mList == null) {
            return 0;
        }
        return mList.size();
    }

    /**
     * 当前是否为最后一页
     */
    public boolean isLastPage() {
        return mLastPage;
    }

    /**
     * 设置是否为最后一页
     */
    public void setLastPage(boolean last) {
        mLastPage = last;
    }

    @Override
    public int getItemCount() {
        // 判断数据是否空，如果没有数据，并且需要显示空布局，就返回1。
        int count = mList != null ? mList.size() : 0;
        if (count > 0) {
            return count;
        } else {
            // 显示空布局
            return 1;
        }
    }

    /**
     * 判断是否是空布局
     */
    public boolean isEmptyPosition(int position) {
        int count = mList != null ? mList.size() : 0;
        return position == 0  && count == 0 ;
    }

    /**
     * 是否空布局
     *
     * @return
     */
    public boolean isShowEmptyView() {
        return mList == null || mList.size()<=0;
    }

    //如果是使用GridLayoutManager，为了能让空布局铺面RecyclerView，需要setSpanSizeLookup。
    //
    //    final GridLayoutManager layoutManager = new GridLayoutManager(this, 2);
    //    layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
    //        @Override
    //        public int getSpanSize(int position) {
    //            // 如果是空布局，让它占满一行
    //            if (mAdapter.isEmptyPosition(position)) {
    //                return layoutManager.getSpanCount();
    //            }
    //            return 1;
    //        }
    //    });
    //    rvList.setLayoutManager(layoutManager);

    /**
     * 绑定布局ID
     *
     * @return
     */
    protected abstract int bindLayoutId();

    /**
     * 绑定空布局Id
     *
     * @return
     */
    protected int bindNullLayoutId() {
        return nullLayoutId;
    }

    @NonNull
    @NotNull
    @Override
    public RVBaseViewHolder onCreateViewHolder(@NonNull @NotNull ViewGroup parent, int viewType) {
        RVBaseViewHolder baseViewHolder = null;
        if (viewType == TYPE_EMPTY) {
            // 创建空布局item
            baseViewHolder = new RVBaseViewHolder(getEmptyView(parent));
        } else {
            // 创建普通的item
            baseViewHolder =  new RVBaseViewHolder(getView(parent));
        }
        baseViewHolder.setAdapter(this);
        return baseViewHolder;
    }

    public void setEmptyView( ViewGroup viewGroup) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.adapter_null, viewGroup, false);
        setEmptyView(view);
    }

    public void setEmptyView(int layoutResId, ViewGroup viewGroup) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(layoutResId, viewGroup, false);
        setEmptyView(view);
    }


    public void setEmptyView(View emptyView) {
        int oldItemCount = getItemCount();
        boolean insert = false;
        if (mEmptyLayout == null) {
            mEmptyLayout = new FrameLayout(emptyView.getContext());
            final ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            final ViewGroup.LayoutParams lp = emptyView.getLayoutParams();
            if (lp != null) {
                layoutParams.width = lp.width;
                layoutParams.height = lp.height;
            }
            mEmptyLayout.setLayoutParams(layoutParams);
            insert = true;
        }
        mEmptyLayout.removeAllViews();
        mEmptyLayout.addView(emptyView);
        if (insert && getItemCount() == 0) {
            int position = 0;
            if (getItemCount() > oldItemCount) {
                notifyItemInserted(position);
            } else {
                notifyDataSetChanged();
            }
        }
    }

    /**
     * 获取空布局
     */
    private View getEmptyView(ViewGroup parent) {
        return LayoutInflater.from(parent.getContext()).inflate(bindNullLayoutId(), parent, false);
    }

    /**
     * 获取正常布局
     */
    private View getView(ViewGroup parent) {
        return LayoutInflater.from(parent.getContext()).inflate(bindLayoutId(), parent, false);
    }

    @Override
    public int getItemViewType(int position) {
        if (isEmptyPosition(position)) {
            // 空布局
            return TYPE_EMPTY;
        } else {
            return TYPE_ITEM;
        }
    }

    /**
     * @param holder
     * @param position
     */
    @Override
    public void onBindViewHolder(@NonNull @NotNull RVBaseViewHolder holder, int position) {
        // 如果是空布局item，不需要绑定数据
        if (!isEmptyPosition(position)) {
            convert(holder, mList, mList.get(position), holder.getLayoutPosition());
        } else {
            convert(holder);
        }

        if (holder.getChildClickViewIds() == null || holder.getChildClickViewIds().size() <= 0 && mEmptyLayout == null) {
            holder.getItemView().setOnClickListener(view -> {
                if (mList == null || mList.size() <= 0) {
                    return;
                }
                setOnItemClick(view, mList.get(position), position);
            });
        }


        if (holder.getChildLongClickViewIds() == null || holder.getChildLongClickViewIds().size() <= 0 && mEmptyLayout == null) {
            holder.getItemView().setOnLongClickListener(view -> {
                if (mList == null) {
                    setOnItemLongClickListener(view, null, 0);
                } else {
                    setOnItemLongClickListener(view, mList.get(position), position);
                }
                return false;
            });
        }

    }

    public abstract void convert(RVBaseViewHolder holder, List<T> mList, T t, int position);

    //空不局绑定点击事件使用
    public abstract void convert(RVBaseViewHolder holder);

    private void setOnItemClick(View v, T t, int position) {
        //点击事件是否进行初始化操作
        if (mOnItemClickListener != null) {
            if (isFastClick()) {
                return;
            }
            mOnItemClickListener.onItemClick(this, v, t, position);
        }
    }

//    private void setOnItemClick(View v) {
//        //点击事件是否进行初始化操作
//        if (mOnItemClickListener != null) {
//            if (isFastClick()) {
//                return;
//            }
//            mOnItemClickListener.onItemClick(this, v);
//        }
//    }

    private boolean setOnItemLongClickListener(View view, T t, int position) {
        if (mOnItemLongClickListener != null) {
            return mOnItemLongClickListener.onItemLongClick(this, view, t, position);
        }
        return false;
    }


    /************************************* Add Listener ****************************************/

    /*
     * addChildClickViewIds使用方法
     */
//     adapter.addChildClickViewIds(R.id.img, R.id.tweetName, R.id.tweetText);
//        adapter.setOnItemChildClickListener(new OnItemChildClickListener() {
//            @Override
//            public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
//                String content = null;
//                Status status = (Status) adapter.getItem(position);
//                switch (view.getId()) {
//                    case R.id.img:
//                        content = "img:" + status.getUserAvatar();
//                        break;
//                    case R.id.tweetName:
//                        content = "name:" + status.getUserName();
//                        break;
//                    case R.id.tweetText:
//                        content = "tweetText:" + status.getUserName();
//                        break;
//                    default:
//                        break;
//                }
//                Tips.show(content);
//            }
//        });


    /************************************** Set Listener ****************************************/

    public void setOnItemClick(OnItemClickListener<T> click) {
        this.mOnItemClickListener = click;
    }

    public void setOnItemLongClickListener(OnItemLongClickListener<T> longClickListener) {
        this.mOnItemLongClickListener = longClickListener;
    }

    @Nullable
    public final OnItemClickListener<T> getOnItemChildClickListener() {
        return mOnItemClickListener;
    }

    @Nullable
    public final OnItemLongClickListener<T> getOnItemLongChildClickListener() {
        return mOnItemLongClickListener;
    }

    // 两次点击按钮之间的点击间隔不能少于1000毫秒
    private static final int MIN_CLICK_DELAY_TIME = 500;
    private static long lastClickTime;

    private static boolean isFastClick() {
        boolean flag = false;
        long curClickTime = System.currentTimeMillis();
        if ((curClickTime - lastClickTime) <= MIN_CLICK_DELAY_TIME) {
            flag = true;
        }
        lastClickTime = curClickTime;
        return flag;
    }
}